import numpy as np

def is_app(row):
    return True if row['site_id'] == '85f751fd' else False


def def_user(row):
    if row['device_id'] == 'a99f214a':
        user = 'ip-' + row['device_ip'] + '-' + row['device_model']
    else:
        user = 'id-' + row['device_id']

    return hash(user) % 1e8


def get_hist(data):
    #     pub_id_dict = collections.defaultdict(list)
    #     pub_domain_dict = collections.defaultdict(list)
    #     pub_category_dict = collections.defaultdict(list)
    pub_id_dict = {}
    pub_domain_dict = {}
    pub_category_dict = {}

    pub_id_list = []
    pub_domain_list = []
    pub_category_list = []
    for tup in data.itertuples():
        # 先试一下纯行为序列，不考虑 click 是否为 1
        user = tup.user
        if user not in pub_id_dict:
            pub_id_dict[user] = [0, 0, 0, 0, 0]
        else:
            if tup.click == 1:
                pub_id_dict[user].append(tup.pub_id)
                pub_id_dict[user].pop(0)

        #         if user in pub_id_dict:
        #             pub_id_dict[user].append(tup.pub_id)
        #             pub_id_dict[user].pop(0)
        #         else:
        #             pub_id_dict[user] = [-1, -1, -1, tup.pub_id]

        if user not in pub_domain_dict:
            pub_domain_dict[user] = [0, 0, 0, 0, 0]
        else:
            if tup.click == 1:
                pub_domain_dict[user].append(tup.pub_domain)
                pub_domain_dict[user].pop(0)
        #         if user in pub_domain_dict:
        #             pub_domain_dict[user].append(tup.pub_domain)
        #             pub_domain_dict[user].pop(0)
        #         else:
        #             pub_domain_dict[user] = [-1, -1, -1,tup.pub_domain]

        if user not in pub_category_dict:
            pub_category_dict[user] = [0, 0, 0, 0, 0]
        else:
            if tup.click == 1:
                pub_category_dict[user].append(tup.pub_category)
                pub_category_dict[user].pop(0)
        #         if user in pub_category_dict:
        #             pub_category_dict[user].append(tup.pub_category)
        #             pub_category_dict[user].pop(0)
        #         else:
        #             pub_category_dict[user] = [-1, -1, -1, tup.pub_category]

        pub_id_list.append(pub_id_dict[user][:4].copy())
        pub_domain_list.append(pub_domain_dict[user][:4].copy())
        pub_category_list.append(pub_category_dict[user][:4].copy())

    pub_id_list = np.array(pub_id_list, dtype=np.int32)
    pub_domain_list = np.array(pub_domain_list, dtype=np.int32)
    pub_category_list = np.array(pub_category_list, dtype=np.int32)

    return pub_id_list, pub_domain_list, pub_category_list

def set_imbalance_other(data,name):
    name_count = data[name].value_counts()
    name_others = name_count.loc[name_count <10].index
    value = -100
    data.loc[data[name].isin(name_others), name] = value
